package com.xx.jicheng.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xx.jicheng.entity.Item;
import com.xx.jicheng.service.CartService;
import com.xx.jicheng.service.ConfigService;

@Service
public class CartServiceImpl implements CartService {
	
	@Autowired
	@Qualifier("commonRedisTemplate")
	private RedisTemplate<String, Object> template;

	@Transactional
	@Override
	public void updateItem(String accountNo, int productId, int amount, String name, double price, String image) {
		String key = ConfigService.CART_PREFIX+accountNo;
		String keyinfo = "item.info." + productId;		
		String keyamount = "item.amount." + productId;
		template.boundHashOps(key).putIfAbsent(keyinfo, name+"_"+price+"_"+image);
		Long a = template.boundHashOps(key).increment(keyamount, amount);
		if(a<=0) {
			template.boundHashOps(key).delete(keyinfo, keyamount);
		}
	}

	@Override
	public void removeItem(String accountNo, int productId) {
		String key = ConfigService.CART_PREFIX+accountNo;
		String keyinfo = "item.info." + productId;		
		String keyamount = "item.amount." + productId;
		template.boundHashOps(key).delete(keyinfo, keyamount);
	}

	@Override
	public void clearCart(String accountNo) {
		String key = ConfigService.CART_PREFIX+accountNo;
		template.delete(key);
	}

	@Override
	public Map<Integer, Item> getItems(String accountNo) {
		String key = ConfigService.CART_PREFIX+accountNo;
//		for(Object k: keys) {
//			System.out.println(k.getClass());
//			System.out.println(template.boundHashOps(key).get(k));
//		}
		Map<Object, Object> all = template.boundHashOps(key).entries();
		Map<Integer, Item> r = new HashMap<>();
		for(Entry<Object,Object> entry : all.entrySet()) {
			String k = entry.getKey().toString();
			if(k.startsWith("item.amount.")){
				int productId = Integer.parseInt(k.substring("item.amount.".length()));
				Item i = r.get(productId);
				if(i == null) {
					i = new Item();
				}
				i.setProductId(productId);
				i.setAmount((Integer)entry.getValue());
				r.put(productId, i);
			} else if(k.startsWith("item.info.")) {
				int productId = Integer.parseInt(k.substring("item.info.".length()));
				Item i = r.get(productId);
				if(i == null) {
					i = new Item();
				}
				String info = entry.getValue().toString();
				String[] split = info.split("_");
				i.setName(split[0]);
				i.setPrice(Double.parseDouble(split[1]));
				i.setImage(split[2]);
				r.put(productId, i);
			}
		}
		return r;
	}

}
